package com.shenyi.cloud.rest;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableSet;
import com.shenyi.cloud.dto.Result;
import com.shenyi.cloud.exception.ExceptionConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Date;

/**
 * @author richard.fan
 * @version 1.0
 * @date 2019/02/18
 * @desc 全局返回值
 * @see
 * @since 1.0
 */
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private Logger logger = LoggerFactory.getLogger(GlobalResponseBodyAdvice.class);


    /**
     * swagger请求地址返回不需要处理
     */
    private final ImmutableSet<String> URI_EXCLUDE_SET = new ImmutableSet.Builder<String>()
            .add("/app/swagger-resources")
            .add("/app/v2/api-docs")
            .build();

    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return Boolean.TRUE;
    }

    public Object beforeBodyWrite(Object obj, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (URI_EXCLUDE_SET.contains(((ServletServerHttpRequest) request).getServletRequest().getRequestURI())) {
            return obj;
        }
        if (obj == null || !(obj instanceof Result)) {
            Result result = new Result(ExceptionConstants.SUCCESS, obj);
            result.setServerTime(new Date());
            //String类型单独处理
            if (obj instanceof String) {
                return JSON.toJSONString(result);
            }
            return result;
        }
        return obj;
    }
}
